//
//  InterViewScheduleInfoVC.m
//  FindJob
//
//  Created by apple on 16/3/12.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "InterViewScheduleInfoVC.h"
#import "TimerView.h"
#import "InputTableViewCell.h"
#import "SelectedTableViewCell.h"
#import "InfoSelectView.h"
#import "InterViewModel.h"
#import "SaveInterviewScheduleAPIManger.h"
#import "WaitAlertView.h"

#define kInfoSelectViewHeight 304
@interface InterViewScheduleInfoVC ()<UITableViewDataSource,UITableViewDelegate,TimerViewDelegate,InfoSelectViewDataSource,InfoSelectViewDelegate>
{
    UILabel *_showTimeLabel;
}

@property (nonatomic, strong) SaveInterviewScheduleAPIManger *saveInterviewScheduleAPIManger;
@property (nonatomic, strong) SelectedTableViewCell *selectedCell;
@property (nonatomic, strong) InfoSelectView *selectView;
@property (nonatomic, copy) NSArray *infoDatas;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) TimerView *timerView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, copy) NSArray *titleArr;
@property (nonatomic, copy) NSArray *datas;
@property (nonatomic, copy) NSMutableDictionary *dictM;
@property (nonatomic, copy) NSDictionary *dict;
@property (nonatomic, copy) NSArray *titleKey;

@property (nonatomic, strong) WaitAlertView *waitView;
@property (nonatomic, copy) NSMutableArray *arrayM;

- (void)initializeUserIntefcace;  /**< 初始化用户界面 */
- (void)initializeDataSource;     /**< 初始化数据源 */
@end

@implementation InterViewScheduleInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserIntefcace];
}
- (void)initializeDataSource{
    _dictM = [[NSMutableDictionary alloc] init];
    _titleKey = @[@"scheduleType",@"scheduleCompany",@"scheduleAddress",@"scheduleDate",@"reminderTime",@"remarks",@"personalId"];
}
- (void)initializeUserIntefcace{
    self.tableView.bounces = NO;
    [self.tableView reloadData];
    UINib *selectedNib = [UINib nibWithNibName:NSStringFromClass([SelectedTableViewCell class]) bundle:nil];
    [self.tableView registerNib:selectedNib forCellReuseIdentifier:kSelectedCellIdentifier];
    
    UINib *inputNib = [UINib nibWithNibName:NSStringFromClass([InputTableViewCell class]) bundle:nil];
    [self.tableView registerNib:inputNib forCellReuseIdentifier:kInputTableViewCellIdentifier];
    
    
    
    
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];// 设置中文显示
    self.datePicker.locale = locale;
    
    //当前时间创建NSDate
    NSDate *localDate = [NSDate date];
    //在当前时间加上的时间：格里高利历
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    //设置时间
    [offsetComponents setYear:0];
    [offsetComponents setMonth:0];
    [offsetComponents setDay:5];
    [offsetComponents setHour:20];
    [offsetComponents setMinute:0];
    [offsetComponents setSecond:0];
    //设置最大值时间
    NSDate *maxDate = [gregorian dateByAddingComponents:offsetComponents toDate:localDate options:0];
    //设置属性
    self.datePicker.minimumDate = localDate;
    self.datePicker.maximumDate = maxDate;
     [self.tableView reloadData];
}
#pragma mark - Button

- (IBAction)respondsToBarBtnItem:(UIBarButtonItem *)sender {
    
    NSDictionary *parameter = [[NSDictionary alloc] init];
    parameter = @{@"interviewSchedule":[self gainDatas],@"interviewScheduleId":@"0"};
    [self.saveInterviewScheduleAPIManger startSaveInterViewScheduleRequestWithParameters:parameter responds:^(RespondsStatus status, NSString *message) {
        if (status == RespondsStatusSuccess) {
            NSLog(@"%@",message);
        }else if (status == RespondsStatusDataError){
             NSLog(@"%@",message);
        }else{
             NSLog(@"%@",message);
        }
    }];
}


#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.datas[indexPath.row];
    NSString *key = [dict allKeys][0];
    NSArray *array = dict[key];
    if (array.count == 0) {
        InputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kInputTableViewCellIdentifier];
        cell.titleLabel.text = key;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    SelectedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSelectedCellIdentifier];
    cell.titleLabel.text = key;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.subTitle.text = @"点击选择";
    
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.datas[indexPath.row];
    NSString *key = [dict allKeys][0];
    NSArray *array = dict[key];
    
    if (array.count == 0) {
        InputTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell.inputTextField becomeFirstResponder];
    }else if(array.count == 1){
        if (![self.timerView superview]) {
            [self.view addSubview:self.timerView];
        }
        SelectedTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.selectedCell = cell;

    }
    else{
        self.infoDatas = array;
        if ([self.selectView superview] == nil) {
            [self.view addSubview:self.selectView];
        }
        [self.selectView reloadAllComponents];
        if (self.selectView.numberOfCompents == 0) {
            // 设置默认选择的第一个分区的第0行
            [self infoSelectView:self.selectView didSelectRow:0 inComponent:0];
        }else{
            [self infoSelectView:self.selectView didSelectRow:0 inComponent:1];
        }
    }
    
}
#pragma mark - gainData

- (NSMutableDictionary *)gainDatas {
    // indexPath
    for (int i = 0; i < self.datas.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[InputTableViewCell class]]) {
            InputTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            
            [_dictM setValue:cell.inputTextField.text forKey:_titleKey[i]];
        
        }else{
            SelectedTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            [_dictM setValue:cell.subTitle.text forKey:_titleKey[i]];
        }
    }
    return _dictM;
}
#pragma mark -- 分区
- (NSInteger)numberOfCompentsInSelectView:(InfoSelectView *)infoSelectView{
    
    NSInteger compents = 1;
    for (id value in self.infoDatas) {
        if ([value isKindOfClass:[NSDictionary class]]) {
            compents = 2;
            break;
        }
    }
    return compents;
}
- (NSInteger)infoSelectView:(InfoSelectView *)infoSelectView numberOfRowsInCompent:(NSInteger)compent{
    if (infoSelectView.numberOfCompents == 2) {
        if (compent == 0) {
            return self.infoDatas.count;
        }
        NSInteger selectIndex =  [infoSelectView selectRowInComponet:0];
        
        NSDictionary *dict = self.infoDatas[selectIndex];
        NSArray *array = dict[@"Cities"];
        return array.count;
        
    }else{
        return self.infoDatas.count;
    }
}

#pragma mark -- UITableViewDelegate

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}
- (NSString *)infoSelectView:(InfoSelectView *)infoSelectView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (infoSelectView.numberOfCompents == 2) {
        
        if (component  == 0) {
            NSDictionary *dict = self.infoDatas[row];
            return dict[@"State"];
        }else{
            // 获取第一个分区选中的行
            NSInteger selectedIndex = [infoSelectView selectRowInComponet:0];
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[selectedIndex];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[row];
            return cityInfo[@"city"];
            
        }
    }else{
        // 只要一个分区是直接返回当前的值
        return self.infoDatas[row];
    }
    
}

- (void)infoSelectView:(InfoSelectView *)infoSelectView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    // 获取选中的cell
    SelectedTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
    
    if (infoSelectView.numberOfCompents == 2) {
        NSString *subTitle = @"";
        if (component == 0) {
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[row];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[0];
            subTitle = cityInfo[@"city"];
        }else{
            // 获取第一个分区选中的行
            NSInteger selectedIndex = [infoSelectView selectRowInComponet:0];
            // 获取选中的字典、选中的哪一行
            NSDictionary *dict = self.infoDatas[selectedIndex];
            NSArray *cities = dict[@"Cities"];
            NSDictionary *cityInfo = cities[row];
            subTitle = cityInfo[@"city"];
        }
        cell.subTitle.text = subTitle;
        
    }else{
        cell.subTitle.text = self.infoDatas[row];
    }
    
}


#pragma mark - TimerViewDelegate
- (void)timerView:(TimerView *)timerView didSelectedDate:(NSDate *)date{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    self.selectedCell.subTitle.text = [formatter stringFromDate:date];
}

#pragma mark - getters

- (InfoSelectView *)selectView{
    if (!_selectView) {
        _selectView = [[InfoSelectView alloc] initWithDataSoure:self delegate:self];
    }
    return _selectView;
}
- (NSArray *)datas{
    if (!_datas) {
        InterViewModel *model = [[InterViewModel alloc] init];
        _datas = [model gainInterViewModels];
    }
    return _datas;
}
- (TimerView *)timerView{
    if (!_timerView) {
       
        _timerView = [[TimerView alloc] initWithDelegate:self];
    }
    return _timerView;
}
- (UIDatePicker *)datePicker{
    if (!_datePicker) {
        CGRect frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - kInfoSelectViewHeight, [UIScreen mainScreen].bounds.size.width, kInfoSelectViewHeight);
        _datePicker = [[UIDatePicker alloc] initWithFrame:frame];
        [_datePicker addTarget:self action:@selector(respondsToDateChanged:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}
- (SaveInterviewScheduleAPIManger *)saveInterviewScheduleAPIManger{
    if (!_saveInterviewScheduleAPIManger) {
        _saveInterviewScheduleAPIManger = [[SaveInterviewScheduleAPIManger alloc] init];
    }
    return _saveInterviewScheduleAPIManger;
}

- (WaitAlertView *)waitView{
    if (!_waitView ) {
        _waitView = [[WaitAlertView alloc] init];
    }
    return _waitView;
}

#pragma mark - private
- (void)respondsToDateChanged:(id)sender{
    //NSDate格式转换为NSString格式
    NSDate *pickerDate = [self.datePicker date];// 获取用户通过UIDatePicker设置的日期和时间
    NSDateFormatter *pickerFormatter = [[NSDateFormatter alloc] init];// 创建一个日期格式器
//    [pickerFormatter setDateFormat:@"yyyy年MM月dd日(EEEE)   HH:mm:ss"];
    [pickerFormatter setDateFormat:@"yyyy年MM月dd日(EEEE)"];
    NSString *dateString = [pickerFormatter stringFromDate:pickerDate];
    
    //打印显示日期时间
//    NSLog(@"格式化显示时间：%@",dateString);
    _showTimeLabel.text = dateString;
    self.selectedCell.subTitle.text = dateString;
   
}


@end
